<?php

namespace app\merchant\controller;

use app\merchant\model\MerchantModel;
use app\merchant\model\VerificationModel;
use think\admin\Controller;
use think\admin\model\SystemUser;
use think\admin\service\AdminService;
use think\Exception;
use think\facade\Db;


/**
 * 商户认证管理
 * @class Verification
 * @package app\merchant\controller
 */
class Verification extends Controller
{
    /**
     * 企业认证列表
     * @auth true
     * @menu true
     */
    public function index()
    {
        $this->title = '企业认证列表';
        VerificationModel::mQuery()->with('merchant')
            ->like('company,phone,id_company')
            ->equal('status')
            ->dateBetween('create_at')
            ->order('id desc')
            ->layTable();
    }

    /**
     * 列表数据处理
     * @param array $data
     */
    protected function _index_page_filter(array &$data)
    {

    }

    /**
     * 企业认证详情
     * @auth true
     */
    public function detail()
    {
        $this->vo = VerificationModel::with('merchant')->where('id', $this->request->get('id'))->find();
        $this->fetch();
    }

    /**
     * 添加企业认证
     * @auth true
     */
    public function add()
    {
//        $this->_applyFormToken();
        VerificationModel::mForm('form');
    }

    /**
     * 编辑企业认证
     * @auth true
     */
    public function edit()
    {
//        $this->_applyFormToken();
        VerificationModel::mForm('form');
    }

    /**
     * 表单数据处理
     * @param array $vo
     */
    protected function _form_filter(array &$vo)
    {
        if ($this->request->isGet()) {

        }else{

        }
    }

    /**
     * 审核企业认证
     * @auth true
     */
    public function review()
    {
        if ($this->request->isGet()){
            $this->vo = VerificationModel::with('merchant')->where('id', $this->request->get('id'))->find();
            $this->fetch();
        }else{
            $id = $this->request->post('id');
            $status = $this->request->post('status');
            $review_reason = $this->request->post('review_reason');

            Db::startTrans();
            try {
                $verification = VerificationModel::where('id', $id)->lock(true)->find();
                if (empty($verification)) $this->error('企业认证申请不存在');
                if ($verification->status != 0) $this->error('待审核的申请才能审核');
                if (!in_array($status, [1, -1])) $this->error('审核状态不正确');
                $verification->save([
                    'status' => $status,
                    'review_reason' => $review_reason,
                    'review_at' => date('Y-m-d H:i:s'),
                    'review_admin_id' => AdminService::getUserId(),
                ]);
                // 更新商户的信息
                if ($status == 1){
                    $merchant = MerchantModel::where('is_deleted', 0)->where('id', $verification->merchant_id)->find();
                    $merchant->save([
                        'company' => $verification->company,
                        'phone' => $verification->phone,
                        'id_company' => $verification->id_company,
                        'legal_person' => $verification->legal_person,
                        'legal_person_phone' => $verification->legal_person_phone,
                        'license_img' => $verification->license_img,
                        'is_verification' => 1,
                    ]);
                    if (empty($merchant->system_user_id)){
                        // 创建企业后台账号密码
                        $user = [];
                        $user['usertype'] = 'merchant_admin';
                        $user['contact_phone'] = $verification->phone;
                        // 账号是公司名称，密码是联系电话
                        $user['username'] = $verification->company;
                        $user['nickname'] = $verification->company;
                        $user['password'] = md5($verification->phone);
                        // 固定企业用户的权限为id=2
                        $user['authorize'] = arr2str([2]);
                        // 检查账号是否重复
                        $map = ['username' => $user['username'], 'is_deleted' => 0];
                        $count = 0;
                        while (SystemUser::mk()->where($map)->count() > 0) {
                            $count ++;
                            $map['username'] = $user['username'] . strval($count);
                        }
                        $user = SystemUser::create($user);
                        // 更新绑定的账号
                        $merchant = MerchantModel::where('is_deleted', 0)->where('id', $verification->merchant_id)->find();
                        $merchant->system_user_id = $user->id;
                        $merchant->save();
                    }
                }
                Db::commit();
            }catch (Exception $e){
                Db::callback();
                $this->error($e->getMessage());
            }
            $this->success('保存成功');
        }
    }
}
